package com.example.g7640.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.g7640.builder.ResultBuilder;
import com.example.g7640.dto.CustomerDto;
import com.example.g7640.dto.DeliveryQuery;
import com.example.g7640.dto.common.PageResult;
import com.example.g7640.entity.DeliveryInfo;
import com.example.g7640.enums.UserType;
import com.example.g7640.exception.BizException;
import com.example.g7640.mapper.DeliveryInfoMapper;
import com.example.g7640.service.DeliveryInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.g7640.util.BaseConvertor;
import com.example.g7640.util.PageUtil;
import com.example.g7640.util.RoleCheckUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2024-03-18
 */
@Service
public class DeliveryInfoServiceImpl extends ServiceImpl<DeliveryInfoMapper, DeliveryInfo> implements DeliveryInfoService {

    @Resource
    DeliveryInfoMapper deliveryInfoMapper;

    public Boolean add(DeliveryInfo deliveryInfo) {
        RoleCheckUtil.checkCustomer();
        if (deliveryInfo.getCid() == null) {
            throw new BizException("Customer id is null");
        }
        if (deliveryInfo.getName() == null) {
            throw new BizException("Receiver Name is null");
        }
        if (deliveryInfo.getLocation() == null) {
            throw new BizException("Receiver Location is null");
        }
        if (deliveryInfo.getContact() == null) {
            throw new BizException("Phone number is null");
        }
        deliveryInfo.setCreatedAt(LocalDateTime.now());
        return this.save(deliveryInfo);
    }

    public Boolean delete(Integer id) {
        RoleCheckUtil.checkCustomer();
        return this.removeById(id);
    }

    public Boolean set(DeliveryInfo deliveryInfo) {
        RoleCheckUtil.checkCustomer();
        if (deliveryInfo.getId() == null) {
            throw new BizException("id is null");
        }
        return this.updateById(deliveryInfo);
    }

    public PageResult<List<DeliveryInfo>> getList(DeliveryQuery deliveryQuery) {
        RoleCheckUtil.checkCustomer();
        LambdaQueryWrapper<DeliveryInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeliveryInfo::getCid, deliveryQuery.getCid());
        IPage iPage = deliveryInfoMapper.selectPage(PageUtil.pageToMybatisPage(deliveryQuery), wrapper);
        return PageUtil.mybatisPageToPage(iPage, DeliveryInfo.class);
    }

    public DeliveryInfo getInfo(Integer id) {
        RoleCheckUtil.check(UserType.customer, UserType.vendor);
        if (id == null) {
            throw new BizException("id is null");
        }
        return this.getById(id);
    }
}
